/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rjp.map;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 *
 * @author mwh
 */
public class CachingArraySantaMap extends ArraySantaMap {

    LinkedHashMap<Long, Float> cache;

    final int size = 1000;

    public CachingArraySantaMap(String fn) throws IOException {

        super(fn);

        cache = new LinkedHashMap<Long, Float>(size, 0.75f, true) {
            @Override
            protected boolean removeEldestEntry(Map.Entry<Long, Float> eldest) {

                return size() > size;

            }
        };
    }

    @Override
    public float getDistance(int indexA, int indexB) {
        if (indexA == indexB) {
            return 0;
        }
        long lindexA = (long) indexA;
        long index = (lindexA << 32) | indexB;
        Float dist = cache.get(index);
        if (dist != null) {
            return dist;
        }

        float xdist = xs[indexA] - xs[indexB];
        float ydist = ys[indexA] - ys[indexB];

        dist = (float) Math.sqrt(xdist * xdist + ydist * ydist);
        cache.put(index, dist);
        return dist;

    }
}
